package com.mantru.iotpot.modbus;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.webkit.JavascriptInterface;

import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.eventbus.EventMessage;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.*;
import java.util.*;

public class HttpThread extends Thread
{
	private ApplicationClass ac;
	private String http_url = "", return_json = "", post_data = "";
	private int event_id = 0;
	public HttpThread(ApplicationClass ac, String url, int id)
	{
		this.ac = ac;
		event_id = id;
		http_url = url.trim();
	}
	public HttpThread(ApplicationClass ac, String url, int id, String data)
	{
		this.ac = ac;
		event_id = id;
		http_url = url.trim();
		post_data = data;
	}

	@Override
	public void run()
	{
		try
		{
			if (post_data == null || post_data.length() == 0)
				HttpGet();
			else
				HttpPost();
			String save_type = Common.JSON_GetFieldValue(return_json, "save_type");
			if (save_type.length() > 0)
				ac.OnHttpData(return_json, save_type);
			if (event_id > 0) {
				//判断是共享图片，这里做个缓存图片
				if (event_id == EventMessage.MSG_ID_OnHttpData_Image) {
					try {
						JSONObject json_object = new JSONObject(return_json);
						for (int i=0; i<json_object.getJSONArray("data").length(); i++) {
							String url = json_object.getJSONArray("data").getJSONObject(i).getString("face_image_url");
							String file_name = url.substring(url.lastIndexOf("/") + 1);
							String save_path = Common.GetCacheFilesUrl(ac, file_name);
							if (Common.CheckLocalFileIsExists(save_path.replace("file://", "")) == false) {
								DownFileObject obj = new DownFileObject(url, save_path);
								DownFileThread down = new DownFileThread(ac, url, obj, true);
								down.start();
							} else {
								json_object.getJSONArray("data").getJSONObject(i).put("face_image_url", save_path);
							}
						}
						return_json = json_object.toString();
					}catch (Exception ex){
					}
				}

				EventMessage e = new EventMessage(event_id, return_json);
				EventBus.getDefault().post(e);
			}
		}
		catch(Exception e)
		{
			Log("HttpThread Run Error:" + e.getMessage());
		}
		// this.stop();
	}

	public void Log(String str)
	{
		Date nowDate = new Date();
		SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String log_str = "[" + format.format(nowDate) + "] " + str;

		System.out.println(log_str);
	}

	public void HttpGet()
	{
		HttpApi_HttpGet(http_url);
	}

	public void HttpPost()
	{
		HttpApi_HttpPost(http_url, post_data);
	}

	private int HttpApi_HttpGet(String short_url)
	{
		String http_long_url = Common.API_Server_Url;
		if (short_url.trim().startsWith("?") == false)
			http_long_url += "?";
		if (short_url.trim().toLowerCase().startsWith("http") == false)
			http_long_url += short_url;

		return_json = "";
		int error_code = 0;      //0表示没有发生异异，1表示有异常
		try
		{
			URL url = new URL(http_long_url);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			InputStream is = conn.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			StringBuilder builder = new StringBuilder();
			String line = "";
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
			return_json = builder.toString();
			is.close();
		}
		catch(Exception ex)
		{
			error_code = 1;
			return_json = "error=" + ex.getMessage();
			Log("HttpHtread get-->" + return_json);
		}

		return 0;
	}

	private int HttpApi_HttpPost(String short_url, String post_data)
	{
		String http_long_url = Common.API_Server_Url;
		if (short_url.trim().startsWith("?") == false)
			http_long_url += "?";
		if (short_url.trim().toLowerCase().startsWith("http") == false)
			http_long_url += short_url;

		return_json = "";
		int error_code = 0;      //0表示没有发生异异，1表示有异常
		try
		{
			URL url = new URL(http_long_url);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			OutputStream os = null;
			if (post_data != null && post_data.length() > 0) {
				os = conn.getOutputStream();
				os.write(post_data.getBytes("UTF-8"));
			}
			InputStream is = conn.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			StringBuilder builder = new StringBuilder();
			String line = "";
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
			return_json = builder.toString();
			is.close();
			if (os != null)
				os.close();
		}
		catch(Exception ex)
		{
			error_code = 1;
			return_json = "error=" + ex.getMessage();
		}

		return 0;
	}


}
